package appli;

import gmusic.bo.ReleaseBean;
import gmusic.dao.impl.AlbumGestionImpl;
import gmusic.ma.bo.ReleaseMABean;
import gmusic.ma.dao.MetalArchivesDAO;
import gmusic.ma.dao.impl.MetalArchivesDAOImpl;
import gmusic.ma.services.impl.MetalArchivesServicesImpl;

import org.apache.log4j.Logger;

public class LoadGMRelease extends ApplicationLC {

	public static final String VERSION = "1.0.0.0";

	public static final String VERSION_DATE = "02/02/2009";

	private static final Logger log = Logger.getLogger(LoadGMRelease.class);

	private long releaseMaid;

	public LoadGMRelease(String[] args) throws Exception {

		super();

		if (!controlArguments(args)) {
			afficherUsage();
			arretExecution(1);
		}

		MetalArchivesDAO mad = MetalArchivesDAOImpl.getInstance();
		ReleaseMABean rb = mad.getMAReleaseAndTracks(releaseMaid);
		if (rb == null) {
			log.error("La realse " + releaseMaid + " n'existe pas dans MA");
			arretExecution(1);
		}
		ReleaseBean ab = MetalArchivesServicesImpl.getInstance()
				.transformMABean2GMBean(rb);
		if (ab == null) {
			log.error("La transformation MA --> GM a echouee maid="
					+ releaseMaid);
			arretExecution(1);
		}
		if (AlbumGestionImpl.getInstance().ajouterAlbum(ab) == -1) {
			log.info("La release existe deja dans GM maid=" + releaseMaid);
			arretExecution(1);
		}

		// Copie du cover en local
		MetalArchivesServicesImpl.getInstance().saveCoverToLocalhost(releaseMaid);

		arretExecution(0);
	}

	@Override
	protected void afficherUsage() {
		log.info("Usage : java appli.LoadGMRelease <release_maid>");
	}

	@Override
	protected boolean controlArguments(String[] args) {

		if (args.length != 1) {
			log.error("Nombre d'argments invalide");
			return false;
		}
		String releaseMaidS = args[0];
		log.debug("Argument : " + releaseMaidS);

		try {
			releaseMaid = Long.parseLong(releaseMaidS);
		} catch (NumberFormatException e) {
			log.error("Release MAID invalide : " + releaseMaidS);
			return false;
		}

		return true;
	}

	public static void main(String[] args) throws Exception {

		new LoadGMRelease(args);
	}
}
